<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;
use Kalnoy\Nestedset\NodeTrait;

class Menu extends Model
{
	use NodeTrait;
	
    protected $fillable = [
        'route_path', 'route_name', 'component', 'redirect', 'meta', 'pid', 'path', 'hidden','name',
        'always_show','menu_group', 'icon', 'leaf', 'sort_order', 'link_dpt_id', 'link_field', 'props',
        'pri', 'menu_type'
    ];
    protected $casts = [
        'buttons' => 'array',
        'meta' => 'array',
        'id' => 'string',
        'pid' => 'string',
        'hidden' => 'boolean',
        'leaf' => 'boolean',
        'sort_order' => 'integer',
        'link_field' => 'string',
        'props' => 'boolean',
        'menu_type' => 'string',
    ];
    
	public function getParentIdName()
	{
		return 'pid';
	}

	// Specify parent id attribute mutator
	public function setParentAttribute($value)
	{
		$this->setParentIdAttribute($value);
	}

    public function getTreeCategory($catId=[])
    {
        $query=$this;
        
        if($catId){
        $query = $this->whereNotIn('id',$catId);
        }
        $lists =$query->select(['id as value', 'pid', 'name as label'])->get()->toArray();



        if (!$lists) {
            return [];
        }

        $refs = [];

        foreach ($lists as $k => $v) {
            $refs[$v['value']] = &$lists[$k];
        }

        $root = 0;
        $tree = [];
        foreach ($lists as $k => $v) {
            $parentId = $v['pid'];
            if ($root == $parentId) {
                $tree[] = &$lists[$k];
            } else {
                if (isset($refs[$parentId])) {
                    $parent = &$refs[$v['pid']];
                    $parent['children'][] = &$lists[$k];
                }
            }
        }
        return $tree;
    }

    public function updateChildren($sourcePath,$ppath){
        $this->where('path', 'like', $sourcePath.'%')->update([
            'path'=>DB::raw('replace(path,"'.$sourcePath.'","'.$ppath.'")')
        ]);
    }
    
    public function setComponentAttribute($value) {
        $this->attributes['component'] = trim($value,'/');
    }
    
    public function setRoutePathAttribute($value) {
        $this->attributes['route_path'] = str_replace(['{','}'], [':',''], $value);
    }

    // public function makeRoot()
    // {
    //     $this->setParent(0)->dirtyBounds();

    //     return $this->setNodeAction('root');
    // }

    // protected function setParent($value)
    // {
    //     $this->setParentId($value ? $value->getKey() : 0)
    //         ->setRelation('parent', $value);

    //     return $this;
    // }

    // public function isRoot()
    // {
    //     return $this->getParentId()==0 || is_null($this->getParentId());
    // }

}
